#include "QAbstractTreeNode.h"
#include "QAbstractTreeModel.h"

QAbstractTreeNode::QAbstractTreeNode(QAbstractTreeNode* parent)
    : QObject(parent)
{
    treeModel = NULL;
    m_parent = parent;
    if(m_parent) {
        connect(this, SIGNAL(layoutAboutToBeChanged()), m_parent, SIGNAL(layoutAboutToBeChanged()));
        connect(this, SIGNAL(layoutChanged()), m_parent, SIGNAL(layoutChanged()));
    }
}

QAbstractTreeNode::~QAbstractTreeNode()
{
    qDeleteAll(m_children);
}

QAbstractTreeNode* QAbstractTreeNode::parent()
{
    return m_parent;
}

int QAbstractTreeNode::childCount() const
{
    return m_children.count();
}

QAbstractTreeNode* QAbstractTreeNode::childAt(int index)
{
    if(index < 0 || index >= m_children.count())
        return NULL;
    return m_children.at(index);
}

int QAbstractTreeNode::row() const
{
    if (m_parent)
         return m_parent->m_children.indexOf(const_cast<QAbstractTreeNode*>(this));
     return 0;
}

void QAbstractTreeNode::addChild(QAbstractTreeNode *child)
{
    emit layoutAboutToBeChanged();
    child->setModel(model());
    m_children.append(child);
    emit layoutChanged();
}

void QAbstractTreeNode::insertChild(QAbstractTreeNode* child, int after)
{
    emit layoutAboutToBeChanged();
    m_children.insert(after, child);
    emit layoutChanged();
}

bool QAbstractTreeNode::removeChild(int index)
{
    if(index < 0 || index >= m_children.count())
        return false;
    emit layoutAboutToBeChanged();
    QAbstractTreeNode* nodeToDelete = m_children.takeAt(index);
    emit layoutChanged();
    if(!nodeToDelete)
        return false;
    delete nodeToDelete;
    return true;
}

void QAbstractTreeNode::removeAllChildren()
{
    for(int i = 0; i < m_children.count(); i++) {
        removeChild(i);
    }
}

bool QAbstractTreeNode::insertColumns(int position, int count)
{
    // default implementation
    Q_UNUSED(position)
    Q_UNUSED(count)
    return false;
}

bool QAbstractTreeNode::removeColumns(int position, int count)
{
    // default implementation
    Q_UNUSED(position)
    Q_UNUSED(count)
    return false;
}

Qt::ItemFlags QAbstractTreeNode::flags(int column) const
{
    // default implementation
    Q_UNUSED(column)
    return (Qt::ItemIsEnabled | Qt::ItemIsSelectable);
}

bool QAbstractTreeNode::setData(QVariant data, int column, int role)
{
	//default implementation
    Q_UNUSED(data)
    Q_UNUSED(column)
    Q_UNUSED(role)
    return false;
}

QAbstractTreeModel* QAbstractTreeNode::model()
{
    return treeModel;
}

QModelIndex QAbstractTreeNode::index()
{
    // recursive call through the hierarchical structure.
    // build index according to parent nodes
    return model()->index(row(), 0, (m_parent != NULL) ? m_parent->index() : QModelIndex());
}
